package fate;


import fate.nsa.NSAReader;
import fate.xp3.XP3Entry;
import fate.xp3.XP3Reader;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.DataFormatException;

public class Resource {

    private Map<String, ArchiveEntry> entries = new HashMap<String, ArchiveEntry>();

    public Resource(String dir) throws DataFormatException, IOException {
        File[] files = new File(dir).listFiles();
        Arrays.sort(files, new Comparator<File>() {
            public int compare(File o1, File o2) {
                return String.CASE_INSENSITIVE_ORDER.compare(o1.getPath(), o2.getPath());
            }
        });
        for (File file: files) {
            if (file.isFile()) {
                String path = file.getPath();
                if (path.toLowerCase().endsWith(".xp3")) {
                    for (ArchiveEntry entry: new XP3Reader(path).getEntries()) {
                        entries.put(entry.getName(), entry);
                    }
                }
                else if (path.toLowerCase().endsWith(".nsa")) {
                    for (ArchiveEntry entry: new NSAReader(path).getEntries()) {
                        entries.put(entry.getName(), entry);
                    }
                }
            }
        }
    }

    public byte[] getResource(String name) throws IOException {
        return entries.get(name).read();
    }

    public static void main(String[] args) throws IOException, DataFormatException {
        long start = System.currentTimeMillis();
        new Resource("D:\\Projects\\Special\\libfate\\libfate-py");
        System.out.println(System.currentTimeMillis() - start);
    }
}
